using System.Drawing;
using GTA;
using NativeUI;

namespace CustomPeds.Menus;

public class SpeechMenu : Script
{
	public static UIMenu menu = new UIMenu("", TextSetting.Speech_Menu, new Point(0, -107));
	private static bool isMenuInitialized;

	private static string[] VoiceName;

	private static string DefaultVoice;

	private static Origin origin;

	public SpeechMenu()
	{
		if (!isMenuInitialized)
		{
			Main.pool.Add(menu);
			menu.OnItemSelect += OnItemSelect;
			menu.OnMenuClose += OnMenuClose;
			isMenuInitialized = true;
		}
	}

	public static void InitSpeakMenu()
	{
		if (DressingScript.Dressing == Main.Member.P1)
		{
			origin = Main.P1;
		}
		else
		{
			origin = Main.P2;
		}
		DefaultVoice = origin.skin.Voice;
		menu.Clear();
		SetGenderVoiceArray();
		menu.SetBannerType(new UIResRectangle());
		int currentSelection = 0;
		for (int i = 0; i < VoiceName.Length; i++)
		{
			if (VoiceName[i] == DefaultVoice)
			{
				menu.AddItem(new UIMenuItem("~y~" + VoiceName[i]));
				currentSelection = i;
			}
			else
			{
				menu.AddItem(new UIMenuItem(VoiceName[i]));
			}
		}
		menu.CurrentSelection = currentSelection;
	}

	private void OnItemSelect(UIMenu sender, UIMenuItem item, int index)
	{
		DefaultVoice = menu.MenuItems[index].Text.Replace("~y~", "");
		if (DressingScript.Dressing == Main.Member.P1)
		{
			origin.skin.Voice = (Main.Clone.skin.Voice = DefaultVoice);
			origin.Character.SetVoice(DefaultVoice);
			Main.Clone.Character.SetVoice(DefaultVoice);
			Main.Clone.Character.PlayAmbientSpeech1("CHAT_STATE", immediately: true);
		}
		else
		{
			origin.skin.Voice = DefaultVoice;
			origin.Character.SetVoice(DefaultVoice);
			origin.Character.PlayAmbientSpeech1("CHAT_STATE", immediately: true);
		}
		menu.MenuItems[index].Text = "~y~" + menu.MenuItems[index].Text;
		InitSpeakMenu();
	}

	private static void SetGenderVoiceArray()
	{
		if (origin.Character.Gender == Gender.Male)
		{
			VoiceName = Skin.MALE_VOICE_NAME;
		}
		else
		{
			VoiceName = Skin.FEMALE_VOICE_NAME;
		}
	}

	private void OnMenuClose(UIMenu sender)
	{
		if (DressingScript.Dressing == Main.Member.P1)
		{
			Main.P1 = origin;
		}
		else
		{
			Main.P2 = origin;
		}
		menu.Visible = false;
		menu.RefreshIndex();
	}
}
